package executor;

import basic.JodisDb;
import basic.KeyType;
import operation.StringOperation;
import protocol.*;
import utils.StringUtils;
import java.util.List;

public class StringExecutor implements Executor{

    private StringOperation stringOperation;

    public StringExecutor(JodisDb jodisDb) {
        this.stringOperation = new StringOperation(jodisDb);
    }

    /**
     * 处理String相关的命令
     * @param request
     * @return
     */
    public Response execute(Request request) {
        //命令，如set key value中set是命令，key和value是参数
        String command = request.getCommand();
        //参数
        List<String> arguments = request.getArgs();
        int argSize = arguments.size();
        if(argSize < 1){
            return ErrorResponse.errorArgsNum(command);
        }

        String key = arguments.get(0);
        if (StringUtils.isEmpty(key)) {
            return ErrorResponse.errorArgsNum(command);
        }

        String type = stringOperation.type(key);
        // 类型不匹配
        if (!StringUtils.isEmpty(type) && !StringUtils.equals(type, KeyType.JODIS_STRING)) {
            return ErrorResponse.errorSyntax();
        }

        String res;
        switch (command){
            case ProtocolConstant.STRING_SET:
                if(argSize != 2){
                    return ErrorResponse.errorArgsNum(command);
                }
                stringOperation.set(key,arguments.get(1));
                return SimpleResponse.ok();

            case ProtocolConstant.STRING_GET:
                if (argSize != 1) {
                    return ErrorResponse.errorArgsNum(command, 1, argSize);
                }
                res = stringOperation.get(key);
                return SimpleResponse.simpleResponse(res);
            default:
        }
        return ErrorResponse.errorUnknownCmd(command);
    }
}
